package com.yb.mini.gateway.custom;

import com.alibaba.nacos.common.utils.MapUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 命名方式仿照内置的即可,例如PathRoutePredicateFactory
 * 注意需要加入Spring容器
 * @author yangbiao
 * @date: 2024/03/14
 */
@Component
public class FromTypeRoutePredicateFactory extends AbstractRoutePredicateFactory<FromTypeRoutePredicateFactory.Config> {

    public FromTypeRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(FromTypeRoutePredicateFactory.Config config) {
        return exchange -> {
            final String type = config.getType();
            if (StringUtils.isBlank(type)) {
                return false;
            }
            final ServerHttpRequest request = exchange.getRequest();
            final List<String> strings = request.getHeaders().get(HttpHeaders.FROM);
            if (!CollectionUtils.isEmpty(strings)) {
                return strings.contains(type);
            }
            return false;
        };
    }

    @Getter
    @Setter
    public static class Config {
        private String type;
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("type");
    }

}
